package cn.com.oil.fx;

import cn.com.oil.common.util.FxManager;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import lombok.Getter;

import java.io.IOException;
import java.util.function.Function;


public class FX extends Application {


    @Getter
    private static String name;
    @Getter
    private static String url;

    @Getter
    private static Stage stage;

    public FX(String name, String url) {
        this.name = name;
        this.url = url;
    }

    public FX() {

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.stage = primaryStage;
        // 创建 Scene，并设置 Stage
        Scene scene = commonScene(url);
        primaryStage.setTitle("oil");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public static void openNewWindow(String name, String url) {
        Platform.runLater(() -> {
            Stage newStage = new Stage();
            stage = newStage;
            Scene newScene = commonScene(url);
            newStage.setScene(newScene);
            newStage.setTitle("oil");
            handleStageCloseRequest(newStage);

            newStage.show();
        });
    }


    public static void open() {
        launch();
    }

    // 提取重复代码到一个独立的方法
    private static void handleStageCloseRequest(Stage stage) {
        // 处理舞台关闭的逻辑
        stage.setOnCloseRequest(event -> {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "确定要关闭窗口吗？", ButtonType.YES, ButtonType.NO);
            alert.showAndWait().ifPresent(buttonType -> {
                ((WindowEvent) event).consume(); // 防止立即关闭
                if (buttonType == ButtonType.YES) {
                    if (1 == FxManager.getFxCount()) {

                        // todo 打开的窗口重名
                        stage.close();
                        System.exit(0);
                    } else {
                        // todo 可能之后要填添加处理
                    }
                }
            });

        });
    }

    public static Scene commonScene(String url) {
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webView.setPrefWidth(800);
        webView.setPrefHeight(600);
        // 加载初始网页
        webEngine.load(url);
        StackPane root = new StackPane();
        root.getChildren().add(webView);
        Scene newScene = new Scene(root);
        webView.prefWidthProperty().bind(newScene.widthProperty());
        webView.prefHeightProperty().bind(newScene.heightProperty());
        return newScene;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
